'use strict';
const db = uniCloud.database();
var ip = '';
var _appId = ''
var _wxPayKey = ''
var _wxPayMchId = ''
var _notifyUrl = ''
var isMiniApp = ''
var _appIdApp = ''
var _wxPayKeyApp = ''
const NodeRSA = require('node-rsa') // 需要执行npm install node-rsa才能调用
const querystring = require('querystring') // node自带，无需安装，直接调用
module.exports = {
	/**
	 * 此函数名称
	 * @url user/pub/test1 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			order_id
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------

		const appIds = await db.collection('wx_config').where({
			'key': 'zfbId'
		}).get()
		const wxPayKey = await db.collection('wx_config').where({
			'key': 'zfbPrivateKey'
		}).get()
		
		const appIdsApp = await db.collection('wx_config').where({
			'key': 'zfbIdApp'
		}).get()
		const wxPayKeyApp = await db.collection('wx_config').where({
			'key': 'zfbPrivateKeyApp'
		}).get()
		
		const wxPayMchId = await db.collection('wx_config').where({
			'key': 'zfbBlipayPublicKey'
		}).get()
		const notifyUrl = await db.collection('wx_config').where({
			'key': 'notifyUrl'
		}).get()
		_appId = appIds.data[0].val
		_wxPayKey = wxPayKey.data[0].val
		_appIdApp = appIdsApp.data[0].val
		_wxPayKeyApp = wxPayKeyApp.data[0].val
		_wxPayMchId = wxPayMchId.data[0].val
		_notifyUrl = notifyUrl.data[0].val
		// 业务逻辑开始-----------------------------------------------------------
		// 可写与数据库的交互逻辑等等
		console.log(originalParam.context,'11111111111111111111111')
		const AlipaySdk = require('alipay-sdk').default;
		const AlipayFormData = require('alipay-sdk/lib/form').default
		// TypeScript，可以使用 import AlipaySdk from 'alipay-sdk';
		// 普通公钥模式
		const alipaySdk = new AlipaySdk({

			gateway: "https://openapi.alipay.com/gateway.do",
			appId: originalParam.context.PLATFORM != 'app-plus' ? _appId : _appIdApp,
			// 应用私钥
			privateKey:originalParam.context.PLATFORM != 'app-plus' ? _wxPayKey : _wxPayKeyApp ,
			// 支付宝公钥
			alipayPublicKey: _wxPayMchId,
		});
		let roderInfo = await vk.baseDao.findByWhereJson({
			dbName: "wx_order",
			whereJson: {
				order_id: order_id,
			}
		});
		let vipInfo= roderInfo.vipInfo
		if(originalParam.context.PLATFORM != 'app-plus'){
			const formData = new AlipayFormData()
			// H5 支付接口，生成请求字符串
			formData.setMethod("get")
			// formData.addField("notifyUrl", "http://online_serve_url/paycallback") // 回调地址必须为当前服务的线上地址！
			formData.addField("returnUrl", _notifyUrl + "/#/pages/award-centre/vip/")
			formData.addField("bizContent", {
				body: vipInfo.name || '名称',
				subject: vipInfo.name || '名称',
				outTradeNo:order_id,
				totalAmount: vipInfo.money,
				quitUrl:  _notifyUrl + "/#/pages/award-centre/vip/",
				productCode: "FAST_INSTANT_TRADE_PAY"
			})
			let payModel = originalParam.context.OS == 'windows' ? 'alipay.trade.page.pay' : 'alipay.trade.wap.pay'
			console.log(payModel,'11111111111111111111',originalParam.context.OS)
			var result = await alipaySdk.exec(payModel, {}, {
				formData: formData,
				// validateSign: true
			})
		}else{
			// App 支付接口，生成请求字符串，
			var result = alipaySdk.sdkExec('alipay.trade.app.pay', {
				bizContent: {
					out_trade_no:  order_id,
					product_code: "FAST_INSTANT_TRADE_PAY",
					subject: vipInfo.name || '名称',
					body: vipInfo.name || '名称',
					total_amount: vipInfo.money
				},
				returnUrl: 'https://www.taobao.com'
			})
		}
	

		
		
		res.data = result
		// 业务逻辑结束-----------------------------------------------------------
		return res;

	}
}


/* 商户订单编号*/
function getWxPayOrdrID() {
	var myDate = new Date();
	var year = myDate.getFullYear();
	var mouth = myDate.getMonth() + 1;
	var day = myDate.getDate();
	var hour = myDate.getHours();
	var minute = myDate.getMinutes();
	var second = myDate.getSeconds();
	var msecond = myDate.getMilliseconds(); //获取当前毫秒数(0-999)
	if (mouth < 10) {
		/*月份小于10  就在前面加个0*/
		mouth = String(String(0) + String(mouth));
	}
	if (day < 10) {
		/*日期小于10  就在前面加个0*/
		day = String(String(0) + String(day));
	}
	if (hour < 10) {
		/*时小于10  就在前面加个0*/
		hour = String(String(0) + String(hour));
	}
	if (minute < 10) {
		/*分小于10  就在前面加个0*/
		minute = String(String(0) + String(minute));
	}
	if (second < 10) {
		/*秒小于10  就在前面加个0*/
		second = String(String(0) + String(second));
	}
	if (msecond < 10) {
		msecond = String(String(0) + String(second));
	} else if (msecond >= 10 && msecond < 100) {
		msecond = String(String(0) + String(second));
	}

	var currentDate =
		String(year) +
		String(mouth) +
		String(day) +
		String(hour) +
		String(minute) +
		String(second) +
		String(msecond);
	return currentDate;
}